﻿using System.IO;
using System.Xml.Serialization;

namespace UmengAnalyticsNet.Extension
{
    public static class SettingEx
    {
        public static void Save<T>(this T p_content, string p_fileName)
        {
            var path = PathEx.GetAppDataPathWithKey(p_fileName);

            CheckDirectory(path);

            using (var stream = File.Create(path))
            {
                XmlSerializer xs = new XmlSerializer(typeof(T));
                xs.Serialize(stream, p_content);
            }
        }

        public static T Load<T>(string p_fileName) where T : class
        {
            var path = PathEx.GetAppDataPathWithKey(p_fileName);

            if (!File.Exists(path))
            {
                return null;
            }

            CheckDirectory(path);

            using (var stream = File.OpenRead(path))
            {
                XmlSerializer xs = new XmlSerializer(typeof(T));
                return xs.Deserialize(stream) as T;
            }
        }

        private static void CheckDirectory(string p_path)
        {
            var dir = Path.GetDirectoryName(p_path);
            if (string.IsNullOrEmpty(dir))
            {
                return;
            }

            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }
        }
    }
}